<?php

/**
 * Tracks the pages visited by a user.
 *
 * adapted from codeutopia.net
 *
 * @author     Mon Zafra <monzee at gmail>
 * @copyright  (c)2009 Mon Zafra
 * @category   Mz
 * @package    Mz_Helper
 * @subpackage Action
 * @license    http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version    SVN: $Id: History.php 3 2009-02-18 18:55:27Z monzee $
 * @see        http://codeutopia.net/blog/2008/03/07/tracking-the-users-browsing-history-with-php/
 */
class Mz_Helper_Action_History extends Zend_Controller_Action_Helper_Abstract
{
    const MAX_PAGES = 3;
    protected $_history;

    public function __construct()
    {
        $this->_history = new Zend_Session_Namespace('History');
    }

    protected function _init()
    {
        if (!isset($this->_history->pages)) {
        	$this->_history->pages = array();
        	if (!empty($_SERVER['HTTP_REFERER'])) {
        		$this->_history->pages[] = $_SERVER['HTTP_REFERER'];
        	}
        } else {
            array_splice($this->_history->pages, self::MAX_PAGES);
        }
    }

    public function preDispatch()
    {
    	$this->_init();
        $urlHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('url');
        $history = $this->_history->pages;
    	if (empty($history[0]) || $history[0] != $urlHelper->url()) {
    		array_unshift($this->_history->pages, $urlHelper->url());
    	}
    }

    /**
     * redirects to a page in the history
     *
     * @param int $numPages Number of pages to go back to
     */
    public function goBack($numPages = 1)
    {
        $numPages = $numPages > self::MAX_PAGES ? self::MAX_PAGES : $numPages;
        $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
        $history = $this->_history->pages;
        $redirector->gotoUrl(isset($history[$numPages]) ? $history[$numPages] : $history[0]);
    }

    public function getPrevious($numPages = 1)
    {
        $numPages = $numPages > self::MAX_PAGES ? self::MAX_PAGES : $numPages;
        $history = $this->_history->pages;
        return isset($history[$numPages]) ? $history[$numPages] : null;
    }

    public function getHistory()
    {
    	return $this->_history->pages;
    }

}